<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\uctoo\wechatopen\controller;

use app\BaseController;
use catcher\CatchResponse;
use think\facade\Cache;
use think\facade\Log;
use uctoo\middleware\Auth;
use app\uctoo\model\saas\FastRegister;
use app\uctoo\model\saas\MerchantAccount;
use app\uctoo\model\saas\MgProfile;
use uctoo\ThinkEasyWeChat\Facade;
use uctoo\util\EventHandler\openPlatform\RegisterEventHandler;
use uctoo\validate\Component as ComponentValidate;
use EasyWeChat\OpenPlatform\Application;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;
use catchAdmin\wechatopen\model\AdminApplet;
use catchAdmin\wechatopen\model\Applet;

class Component extends BaseController
{
    protected $openPlatform;
    /**
     * Applet模型对象
     * @var \catchAdmin\wechatopen\model\Applet
     */
    protected $model = null;

    protected $middleware = [
        Auth::class => ['except' => ['authorize']],
    ];

    public function authorizeCheck(){
        $applet = MerchantAccount::where('id',$this->request->user['uid'])->value('applet_appid');
        $this->success('ok',['is_authorized' => $applet ? true :false]);
    }

    /**
     * 授权小程序
     * @param Application $app
     */
    public function authorize(Application $app)
    {
        $url = $app->getPreAuthorizationUrl(config('plat.authorize_callback_url'));
        header('Location:' . $url);
    }


    /**
     * 获取授权
     * @param Application $app
     * @param null $auth_code
     */
    public function getAuthorization(Application $app)
    {
        $auth_code = Request::post('auth_code');
        $creator_id = Request::post('creator_id');
        if (is_null($auth_code)) {
            abort(404);
        }
        $auth = $app->handleAuthorize($auth_code);
        if(!isset($auth['authorization_info'])){
            $this->error('授权错误');
        }
        $appid = $auth['authorization_info']['authorizer_appid'];
        $app_info = $app->getAuthorizer($appid);
       // $this->success('ok',$app_info);
        $this->model = new Applet;
        if (isset($app_info['authorizer_info'])) {

            $this->model->startTrans();
            $applet = $this->model->where('appid', $appid)->find();
            $db_data=[];
            if($applet){       //已存在appid帐号更新admin_id
                $db_data['creator_id'] = $creator_id;
                $db_data['name'] = $app_info['authorizer_info']['nick_name'];
                $db_data['principal'] = $app_info['authorizer_info']['principal_name'];
                $db_data['original'] = $app_info['authorizer_info']['user_name'];
                if (array_key_exists('head_img', $app_info['authorizer_info'])) {
                    $db_data['headface_image'] = $app_info['authorizer_info']['head_img'];
                }else{
                    $db_data['headface_image'] = '';
                }
                $db_data['qrcode_image'] = $app_info['authorizer_info']['qrcode_url'];
                $db_data['status'] = Applet::STATUS_AUTHORIZED;
                $db_data['service_type_info'] = json_encode($app_info['authorizer_info']['service_type_info']);
                $db_data['verify_type_info'] = json_encode($app_info['authorizer_info']['verify_type_info']);
                $db_data['business_info'] = json_encode($app_info['authorizer_info']['business_info']);
                $db_data['func_info'] = json_encode($app_info['authorization_info']['func_info']);
                $db_data['authorizer_access_token'] = $auth['authorization_info']['authorizer_access_token'];
                $db_data['access_token_overtime'] = time()+$auth['authorization_info']['expires_in']-1500;
                $db_data['authorizer_refresh_token'] = $auth['authorization_info']['authorizer_refresh_token'];
                if (array_key_exists('MiniProgramInfo', $app_info['authorizer_info'])) {   //是否是小程序授权
                    $db_data['miniprograminfo'] = json_encode($app_info['authorizer_info']['MiniProgramInfo']);
                    $db_data['signature'] = $app_info['authorizer_info']['signature'];
                    $db_data['typedata'] = 'miniapp';
                }else{
                    $db_data['wechat'] = $app_info['authorizer_info']['alias'];
                    if($db_data['service_type_info'] == 0 || $db_data['service_type_info'] == 1){
                        $db_data['typedata'] = 'serv_account';
                    }else{
                        $db_data['typedata'] = 'sub_account';
                    }
                }
                $result = $this->model->where('appid',$appid)->update($db_data);
            }else{  //新增
                $db_data['appid'] = $app_info['authorization_info']['authorizer_appid'];
                $db_data['creator_id'] = $creator_id;
                $db_data['name'] = $app_info['authorizer_info']['nick_name'];
                $db_data['principal'] = $app_info['authorizer_info']['principal_name'];
                $db_data['original'] = $app_info['authorizer_info']['user_name'];
                if (array_key_exists('head_img', $app_info['authorizer_info'])) {
                    $db_data['headface_image'] = $app_info['authorizer_info']['head_img'];
                }else{
                    $db_data['headface_image'] = '';
                }
                $db_data['qrcode_image'] = $app_info['authorizer_info']['qrcode_url'];
                $db_data['status'] = Applet::STATUS_AUTHORIZED;
                $db_data['service_type_info'] = json_encode($app_info['authorizer_info']['service_type_info']);
                $db_data['verify_type_info'] = json_encode($app_info['authorizer_info']['verify_type_info']);
                $db_data['business_info'] = json_encode($app_info['authorizer_info']['business_info']);
                $db_data['func_info'] = json_encode($app_info['authorization_info']['func_info']);
                $db_data['authorizer_access_token'] = $auth['authorization_info']['authorizer_access_token'];
                $db_data['access_token_overtime'] = time()+$auth['authorization_info']['expires_in']-1500;
                $db_data['authorizer_refresh_token'] = $auth['authorization_info']['authorizer_refresh_token'];
                if (array_key_exists('MiniProgramInfo', $app_info['authorizer_info'])) {   //是否是小程序授权
                    $db_data['miniprograminfo'] = json_encode($app_info['authorizer_info']['MiniProgramInfo']);
                    $db_data['signature'] = $app_info['authorizer_info']['signature'];
                    $db_data['typedata'] = 'miniapp';
                }else{
                    $db_data['wechat'] = $app_info['authorizer_info']['alias'];
                    if($db_data['service_type_info'] == 0 || $db_data['service_type_info'] == 1){
                        $db_data['typedata'] = 'serv_account';
                    }else{
                        $db_data['typedata'] = 'sub_account';
                    }
                }
                $result = $this->model->save($db_data);
            }
            if($result === false){
                $this->model->rollBack();
                $this->error('添加失败');
            }
            // 提交事务
            $this->model->commit();
            //设置为管理员当前选中的applet
            AdminApplet::setApplet($creator_id,$appid);
            $applet = $this->model->where('appid', $appid)->find();  //刷新信息后的applet
            return CatchResponse::success($applet);
        }
        $this->error('帐号授权错误');
    }


    /**
     * 快速注册小程序
     * @param Application $app
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function fastRegister(Application $app)
    {
        $params = $this->request->post();
        try {
            $this->validate($params, ComponentValidate::class);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
        $regModel = new FastRegister();
        $task = $regModel->where(['merchant_id' => $this->request->user['uid']])->field('id,status')->find();
        if ($task && 0 === $task['status']) {
            $this->error('已有创建小程序');
        }
        $data = $params;
        $data['task_sn'] = make_sign(array_intersect_key($params, array_flip(['name', 'code', 'legal_persona_wechat', 'legal_persona_name'])));
        $data['merchant_id'] = $this->request->user['uid'];
        $data['status'] = -2;  // 待校验状态
        $saveFields = ['merchant_id','name', 'code', 'code_type', 'legal_persona_wechat', 'legal_persona_name', 'component_phone', 'task_sn','status'];
        if (!$task) {
            $regModel->allowField($saveFields)->save($data);
        } else {
            $task->allowField($saveFields)->save($data);
        }
        $res = $app->component->registerMiniProgram($params);
        $this->wxResult($res, 'fast_register');
    }

    /**
     * 注册状态查询
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function registerStatusQuery()
    {
        $apply_info = (new FastRegister())->where(['merchant_id' => $this->request->user['uid']])->field('name,code,code_type,legal_persona_wechat,legal_persona_name,component_phone,status')->find();
        if (!$apply_info) {
            $this->error('申请不存在');
        }

        if (0 === $apply_info['status']) {
            // 查询是否填写过小程序信息
            $mg_profile = MgProfile::where('merchant_id',$this->request->user['uid'])->field('id')->find();
            $data['apply_status'] = [
                'errmsg' => '注册成功',
                'status' => $mg_profile ? 2 : 1   // 2 填写过信息  1 小程序注册成功未补充信息
            ];

        }else{
            $err_msg  = $this->parseWxErrMsg('fast_register_query',$apply_info['status']);
            $data['apply_status'] = [
                'errmsg' => $err_msg,
                'status' => (-2 == $apply_info['status']) ? $apply_info['status'] : 0
            ];
        }
        unset($apply_info['status']);
        $data['apply_info'] = $apply_info;
        $this->success('ok',$data);
    }






}
